import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/bloc/chat_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/data/user_data.dart';
import 'package:grint/entity/chat_message.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/widget/black_button.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/report_dialog.dart';
import 'package:grint/utils/whisper.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({super.key});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  final TextEditingController _xiaoxiKongzhi = TextEditingController();
  final ScrollController _gundonKongzhi = ScrollController();
  User? _duifangYonghu;
  bool _isLoadingUser = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _jiazaiDuifangYonghu();
    });
  }

  @override
  void dispose() {
    _xiaoxiKongzhi.dispose();
    _gundonKongzhi.dispose();
    super.dispose();
  }

  // 加载对方用户信息
  Future<void> _jiazaiDuifangYonghu() async {
    final chatState = context.read<ChatCubit>().state;
    if (chatState.currentConversation != null) {
      final authState = context.read<AuthCubit>().state;
      if (authState.currentUser != null) {
        final otherUserId = chatState.currentConversation!.getOtherUserId(
          authState.currentUser!.id,
        );

        final userData = UserData();
        final user = await userData.getUserById(otherUserId);

        if (mounted) {
          setState(() {
            _duifangYonghu = user;
            _isLoadingUser = false;
          });
        }
      }
    } else {
      // 如果没有当前对话，也要结束加载状态
      if (mounted) {
        setState(() {
          _isLoadingUser = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/commonBg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              Row(
                children: [
                  SizedBox(width: 16.w),
                  BlackButton(
                    icon: IconFontIcons.iconArrowLeft,
                    onTap: () => context.pop(),
                  ),
                  const Spacer(),

                  Center(
                    child:
                        _isLoadingUser
                            ? _buildLoadingHeader()
                            : _buildUserHeader(),
                  ),
                  const Spacer(),
                  BlackButton(
                    icon: IconFontIcons.iconReport2,
                    size: 22.sp,
                    onTap: () => _jubaoYonghu(),
                  ),

                  SizedBox(width: 16.w),
                ],
              ),

              SizedBox(height: 16.h),

              Expanded(
                child: Container(
                  height: double.infinity,
                  decoration: BoxDecoration(
                    color: AppColors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(40.r),
                      topRight: Radius.circular(40.r),
                    ),
                  ),
                  child: Column(
                    children: [
                      // 消息列表
                      Expanded(
                        child: BlocBuilder<ChatCubit, ChatState>(
                          builder: (context, chatState) {
                            if (chatState.isLoading) {
                              return const Center(
                                child: CircularProgressIndicator(),
                              );
                            }

                            if (chatState.currentMessages.isEmpty) {
                              return Center(
                                child: Padding(
                                  padding: EdgeInsets.all(32.w),
                                  child: MyText(
                                    text: 'Start your conversation!',
                                    type: TextType.miSans,
                                    fontSize: 16.sp,
                                    color: AppColors.textGrey,
                                    textAlign: TextAlign.center,
                                  ),
                                ),
                              );
                            }

                            return ListView.builder(
                              controller: _gundonKongzhi,
                              padding: EdgeInsets.symmetric(
                                horizontal: 16.w,
                                vertical: 16.h,
                              ),
                              itemCount: chatState.currentMessages.length,
                              itemBuilder: (context, index) {
                                final message =
                                    chatState.currentMessages[index];
                                return _chuangjianXiaoxiQipao(message);
                              },
                            );
                          },
                        ),
                      ),

                      // 输入框区域
                      _chuangjianShuruKuang(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 创建消息气泡
  Widget _chuangjianXiaoxiQipao(ChatMessage message) {
    final authState = context.read<AuthCubit>().state;
    final isCurrentUser = authState.currentUser?.id == message.senderId;

    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isCurrentUser) ...[
            // 对方头像
            CircleAvatar(
              radius: 16.w,
              backgroundImage: AssetImage(
                _duifangYonghu?.avatar ?? 'assets/images/avatar-one.png',
              ),
            ),
            SizedBox(width: 8.w),
          ],

          // 消息内容
          Flexible(
            child: Row(
              mainAxisAlignment:
                  isCurrentUser
                      ? MainAxisAlignment.end
                      : MainAxisAlignment.start,
              children: [
                Flexible(
                  child: Column(
                    crossAxisAlignment:
                        isCurrentUser
                            ? CrossAxisAlignment.end
                            : CrossAxisAlignment.start,
                    children: [
                      Container(
                        constraints: BoxConstraints(
                          maxWidth: 260.w, // 限制最大宽度，为头像留出空间
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 12.h,
                        ),
                        decoration: BoxDecoration(
                          color:
                              isCurrentUser
                                  ? const Color(0xFFB3E5FC)
                                  : const Color(0xFFF5F5F5),
                          borderRadius: BorderRadius.circular(16.r),
                        ),
                        child: MyText(
                          text: message.content,
                          type: TextType.miSans,
                          fontSize: 14.sp,
                          color: Colors.black87,
                          maxLines: null, // 允许多行显示
                          overflow: TextOverflow.visible, // 确保文本完全显示
                        ),
                      ),

                      SizedBox(height: 4.h),

                      // 时间显示
                      MyText(
                        text: _formatMessageTime(message.createdAt),
                        type: TextType.miSans,
                        fontSize: 12.sp,
                        color: AppColors.textGrey,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          if (isCurrentUser) ...[
            SizedBox(width: 8.w),
            CircleAvatar(
              radius: 16.w,
              backgroundImage: AssetImage(
                authState.currentUser?.avatar ?? 'assets/images/avatar-one.png',
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 创建输入框
  Widget _chuangjianShuruKuang() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(color: AppColors.white),
      child: SafeArea(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: const Color(0xFFF5F5F5),
            borderRadius: BorderRadius.circular(30.r),
          ),
          child: Row(
            children: [
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: TextField(
                    controller: _xiaoxiKongzhi,
                    decoration: InputDecoration(
                      hintText: 'Type A Message...',
                      hintStyle: TextStyle(
                        color: AppColors.textGrey.withValues(alpha: 0.6),
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w400,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 14.h),
                      isDense: true,
                    ),
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.black87,
                      fontWeight: FontWeight.w400,
                    ),
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => _fasongXiaoxi(),
                  ),
                ),
              ),

              BlocBuilder<ChatCubit, ChatState>(
                builder: (context, chatState) {
                  return GestureDetector(
                    onTap: chatState.isSending ? null : _fasongXiaoxi,
                    child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                        color: Colors.black,
                        shape: BoxShape.circle,
                      ),
                      child: Center(
                        child:
                            chatState.isSending
                                ? SizedBox(
                                  width: 18.w,
                                  height: 18.w,
                                  child: const CircularProgressIndicator(
                                    strokeWidth: 2,
                                    color: Colors.white,
                                  ),
                                )
                                : Icon(
                                  IconFontIcons.iconSend,
                                  color: Colors.white,
                                  size: 18.w,
                                ),
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _fasongXiaoxi() {
    final content = _xiaoxiKongzhi.text.trim();
    if (content.isEmpty) return;

    final authState = context.read<AuthCubit>().state;
    if (authState.currentUser == null) return;

    context.read<ChatCubit>().sendMessage(
      content: content,
      senderId: authState.currentUser!.id,
    );

    _xiaoxiKongzhi.clear();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_gundonKongzhi.hasClients) {
        _gundonKongzhi.animateTo(
          _gundonKongzhi.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  String _formatMessageTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } else if (difference.inHours > 0) {
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } else {
      return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    }
  }

  void _jubaoYonghu() {
    if (_duifangYonghu == null) {
      return;
    }

    FankuiTanchuangBangzhu.xianshi(
      context,
      mubiaoyonghuId: _duifangYonghu!.id,
      onJubao: (jubaoLeixing, fujiaxinxi) {
        _chuliYonghuJubao(jubaoLeixing, fujiaxinxi);
      },
    );
  }

  // 处理用户举报
  Future<void> _chuliYonghuJubao(
    JubaoLeixing jubaoLeixing,
    String? fujiaxinxi,
  ) async {
    if (_duifangYonghu == null) return;

    try {
      final chatCubit = context.read<ChatCubit>();
      final authState = context.read<AuthCubit>().state;

      if (authState.currentUser == null) {
        Whisper.hiss('user not login');
        return;
      }

      final currentConversation = chatCubit.state.currentConversation;
      if (currentConversation != null) {
        await chatCubit.deleteConversation(
          currentConversation.id,
          authState.currentUser!.id,
        );
        if (mounted) {
          context.pop();
        }
      } else {}
    } catch (e) {
      // 删除出错
    }
  }

  /// 构建加载中的头部
  Widget _buildLoadingHeader() {
    return Row(
      children: [
        // 加载中的头像占位符
        Container(
          width: 40.w,
          height: 40.w,
          decoration: BoxDecoration(
            color: Colors.grey.shade300,
            shape: BoxShape.circle,
          ),
          child: Center(
            child: SizedBox(
              width: 20.w,
              height: 20.w,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                color: Colors.grey.shade500,
              ),
            ),
          ),
        ),

        SizedBox(width: 9.w),

        // 加载中的名字占位符
        Container(
          width: 80.w,
          height: 16.h,
          decoration: BoxDecoration(
            color: Colors.grey.shade300,
            borderRadius: BorderRadius.circular(8.r),
          ),
        ),

        SizedBox(width: 16.w),
      ],
    );
  }

  /// 构建用户信息头部
  Widget _buildUserHeader() {
    return Row(
      children: [
        // 用户头像
        CircleAvatar(
          radius: 20.w,
          backgroundImage: AssetImage(
            _duifangYonghu?.avatar ?? 'assets/images/avatar-one.png',
          ),
        ),

        SizedBox(width: 9.w),

        // 用户名字
        MyText(
          text: _duifangYonghu?.name ?? 'Unknown User',
          type: TextType.rubik,
          fontSize: 16.sp,
          fontWeight: FontWeight.bold,
          color: Colors.black,
        ),

        SizedBox(width: 16.w),
      ],
    );
  }
}
